<template>
    <view class="bg-[#f8f8f8]  min-h-screen">
        <view class="h-[10rpx]"></view>
        <view class="bg-white px-[40rpx] py-[20rpx]">
            <view class="py-[20rpx] border-b border-[#D8D8D8]">
                <view class="text-center text-[38rpx]">{{classInfo.data.className}}</view>
                <view class=" flex justify-between items-center">
                    <view>定位:{{classInfo.data.location}}</view>
                    <u-icon name="map-fill" color="#007AFF" size="18"></u-icon>
                </view>
                <view class="mt-[10rpx]">描述：{{classInfo.data.address}}</view>
                <view class="mt-[10rpx]">
                <view class=" flex justify-between items-center">课程分类：
                     <uni-data-select   
                     v-model="classInfo.data.subjectlv_id"
                        :localdata="classInfo.range" 
                        @change="classInfo.change"
                      ></uni-data-select>
                      </view>
                </view>
            </view>
            <!-- <uni-forms ref="baseForm" :modelValue="baseFormData"> --> 
            <view v-for="(item, index) in classInfo.model"  class="mt-[20rpx] bg-[#EFEFEF] px-[20rpx] py-[20rpx]">
                <view class="flex justify-between items-center pt-[20rpx]" >
<!--               <input type="checkbox" :value="classesData" @change="classInfo.handleChange(item.classes_id)" :checked="item.classes_id === classInfo.classId" ></input> -->
                 <checkbox-group   @change="classInfo.getChecked(item)">
                      <checkbox  :checked="item.classes_id === classInfo.classId" />
                    </checkbox-group>
                <view class="border-b border-[#D8D8D8]">
                    <view class="pb-[20rpx]">{{item.course_name}}</view>
                    <view class="pb-[20rpx]">课程分类：{{item.subject_name}}</view>
                    <view class="pb-[20rpx]">说明：{{item.description}}</view> 
                </view>
                
                <view class="flex justify-between items-center pt-[20rpx]">
                    <view>
                        <text>费用：</text>
                        <text class="text-[#FD755D]">{{item.price}}元</text>
                    </view>
                    <view>剩余名额：{{item.remaining_slots}}</view>
                </view>
              </view>
            </view> 
          
        </view>  
            <view class="h-[104rpx] w-[100vw] flex justify-around items-center bg-white fixed bottom-0 z-[9999]" :style="{paddingBottom:iosHight+'rpx',height:(104+iosHight)+'rpx'}">
                <view @click="classInfo.submitSignUp"
                      class="w-[208rpx] rounded font-medium text-[30rpx] px-1 bg-[#FD755D] text-white h-[88rpx] flex justify-center items-center">
                        报名</view>
                </view>
            </view> 
</template>
<script setup>
  import Tabbar from "@/components/tabbar.vue";
    import noLogin from "@/components/noLogin.vue";
    import api from "@/api/api"
    import localRegistrationDetails from "@/api/localRegistrationDetails" 
    import Home from "@/api/Home"
    import { useUserStore } from '@/stores/userinfo'
    import { ref, reactive } from "vue" 
    import EventDetails from "@/api/EventDetails" 
    const classesData =ref(false)
    
    onLoad((options) => {
      classInfo.classId = options.classes_id 
      })
    
  const classInfo = reactive({ 
    model: [],
    classId: '',
    data: [],
    range: [],
    changeList: [],
    handleChange:async (e) =>{
     // debugger
      console.log(e)
    },
    getClassInfo:async() =>{  
      if(classInfo.classId  ===''){
        uni.showLoading({ title: '请传班级ID' })
        return
      } 
      const {code,msg,data} = await EventDetails.getClassInfo({
        classes_id: classInfo.classId
      })  
      if (code === 200) {
             classInfo.data=data  
             classInfo.getRange(data) 
             classInfo.getCourseDetailsBySubject(data.subjectlv_id)
      }else{
              uni.showToast({ title: "数据异常" }) 
      }
    },
  
      changeList: async (e) =>{
        console.log(e)
      },
      getRange: async (datas) =>{
          const {msg,code ,data} = await localRegistrationDetails.getSubjectlv({
            latitude:  datas.latitude ,
            longitude:   datas.longitude 
          })
          if(code == 200 && data){
            classInfo.range = data
            console.log(classInfo.range)
          }
      },
      change: async (e) =>{
        classInfo.getCourseDetailsBySubject(e)
      },
      //分类查询
      getCourseDetailsBySubject:async (e) =>{ 
        const {msg,code ,data} = await localRegistrationDetails.getCourseDetailsBySubject({
          subjectlv_id:e 
        })
        if(code == 200 && data){
          classInfo.model = data
          classInfo.model.forEach(item  =>{ 
              if(item.classes_id == classInfo.classId){ 
                item.checked =true
                classesData.value = []
                classesData.value.push(classInfo.classId)
              }else{
                item.checked =false
              }
          }) 
          console.log(classInfo.model)
        }else{
          uni.showToast({
            title: '未查询到数据',
          })
        }
        
      },
      getChecked: async ( item)=>{  
     /*   item.checked = !item.checked
        classesData.value = classInfo.model.every(item => {
        						return item.checked === true
        					}) */
        item.checked = !item.checked
                if (!item.checked) {
                  classesData.value = false
                } else {
                  // 判断每一个商品是否是被选择的状态
                  const goods = classInfo.model.every(item => {
                    return item.checked === true
                  })
                  if (goods) {
                    classesData.value = true
                  } else {
                    classesData.value = false
                  }
                }
                 
       
      },
      submitSignUp: async () =>{
       console.log(classesData.value) 
        //提交
      /*  uni.showToast({
          title: '未查询到数据',
        }) */
        
        const arraData = []
        classInfo.model.forEach(item =>{
          if(item.checked == true){
            arraData.push(item.classes_id)
          }
        })
        
        const resData = await localRegistrationDetails.applyEnrollment( 
          { classes_id:arraData  } ) 
        if(resData.code == 200){
          if( resData.data.OrderData != null ){
            const respay = await localRegistrationDetails.createPrePayOrder(
               {order_id:resData.data.OrderData.id }
             )
             //debugger
             if(respay != null){
               //请求支付页面 
                  //debugger
                 /* ===== ===========start==========*/
                const orderInfox = {
                  appid: respay.data.appId,  // 应用ID（AppID）
                  signtype: respay.data.signType,      // 商户号（PartnerID）
                  //"partnerid": "1648407769", // 预支付交易会话ID
                  package: respay.data.package,        // 固定值
                  noncestr: respay.data.nonceStr, // 随机字符串
                  timestamp: Number(respay.data.timeStamp),        // 时间戳（单位：秒）
                  paysign:  respay.data.paySign, // 签名，这里用的 MD5 签名
                };
                console.log(orderInfox) 
                
                wx.requestPayment
                (
                  {
                    "timeStamp": Number(respay.data.timeStamp),
                    "nonceStr": respay.data.nonceStr,
                    "package": respay.data.package,
                    "signType": respay.data.signType,
                    "paySign": respay.data.paySign, 
                    "success":function(res){
                      debugger
                            console.log('支付成功', res);
                    },
                    "fail":function(res){
                      debugger
                             console.error('支付失败', err);
                    },
                    "complete":function(res){
                      debugger
                            console.log('complete', res);
                    }
                  }
                )
                
                
                
                 // 调用 wx.requestPayment 接口调起支付
                 
          /*       wx.requestPayment({
                   timeStamp: Number(respay.data.timeStamp,),
                   nonceStr: respay.data.nonceStr,
                   package: respay.data.package, 
                   signType: respay.data.signType,
                   paySign: respay.data.paySign,
                   success(res) {
                     console.log('支付成功', res);
                   },
                   fail(err) {
                     console.error('支付失败', err);
                   }
                 }); */

                 
                 /* uni.requestPayment({
                                 provider: "wxpay",  //固定值为"wxpay"
                                orderInfo: orderInfox,
                                    
                            
                                 success: function (res) { 
                                     debugger
                                    console.log(res);
                                     var rawdata = JSON.parse(res.rawdata);
                                     console.log("支付成功");
                                 },
                                 fail: function (err) {
                                   debugger
                                              console.log(err);
                                     console.log('支付失败:' + JSON.stringify(err));
                                 },
                                 }) */
                 /* uni.requestPayment({
                     timeStamp: respay.timestamp ,
                     nonceStr: respay.noncestr,
                     package: respay.package,
                     signType: respay.signType,
                     paySign: respay.sign,
                     success (res) {
                       debugger
                         // 支付成功的处理逻辑
                         console.log('支付成功', res);
                         uni.showToast({
                             title: '支付成功',
                             icon: 'success'
                         });
                         // 可以在这里跳转到订单详情页或其他页面
                         uni.navigateTo({
                             url: '/pages/eventDetails/eventDetails?classes_id='+classInfo.classId
                         });
                     },
                     fail (err) {
                         // 支付失败的处理逻辑
                         console.log('支付失败', err);
                         uni.showToast({
                             title: '支付失败，请重试',
                             icon: 'none'
                         });
                         }
                  }); */
                 
                /* ===== ===========end==========*/
                 
                
             }else{
                uni.showToast({
                  title: resPay.msg,
                })
             }
          }
         
            // uni.showToast({
            //   title: '报名成功',
            // })
           // navigateTo('/pages/eventDetails/eventDetails?classes_id='+classInfo.classId)
        }else{
          uni.showToast({
            title: resData.msg,
          })
        }
      }
    })
    onMounted(classInfo.getClassInfo)

</script>